<?php
namespace app\api\controller\datascreen;

use app\api\controller\Base;
use app\common\model\user\User as UserModel;
use app\common\model\company\Company;
use app\common\model\orderhawa\Hawa;
use app\common\model\orderhawa\HawaList;
use app\common\model\orderreceipt\Receipt;
use app\common\model\orderreceipt\ReceiptList;
use app\api\controller\mytool\Setting;
use think\facade\Request;
use Firebase\JWT\JWT;
use app\common\model\customer\Customervisit;
use app\common\model\company\Contract;
use app\common\model\customer\Customer as Customermodel;
class Customer extends Base
{
    /**
     * 产生jwt加密串，参考session
     */
    public function initialize()
    {
        parent::initialize();
    }

    //宏观数据：今天、昨天、本周、上周、本月、上个月、今年、所有的数据 合同数，客户跟进数,收集订单，入库订单
    /**
     * 统计联单量
     * @return [type] [description]
     */
    public function sumcount()
    {
        self::is_login();
        $thisyear    = date('Y');
        $thismonth   = date('m');
        $thisday     = date('d');
        $thisweekday = date('w');
        $list        = ['today','yesterday','week','lastweek','month','lastmonth','year'];
        $rdata       = [];
        foreach ($list as $lk => $lv) {
            $hawalist    = HawaList::where('State', HawaList::STATEOK);
            $receiptlist = ReceiptList::where('State', ReceiptList::STATEOK);
            $contract = Contract::where('State', Contract::STATEOK);
            $customer = Customervisit::group('CustomerId');
            switch ($lv) {
                case 'year':
                    //php获取本年起始时间戳和结束时间戳
                    $begin = mktime(0, 0, 0, 1, 1, $thisyear);
                    $end   = mktime(23, 59, 59, 12, 31, $thisyear);
                    break;
                case 'today':
                    //今天
                    $begin = mktime(0, 0, 0, $thismonth, $thisday, $thisyear);
                    $end = mktime(23, 59, 59, $thismonth, $thisday, $thisyear);
                break;
                case 'yesterday':
                    //php获取昨日起始时间戳和结束时间戳
                    $begin = mktime(0, 0, 0, $thismonth, $thisday - 1, $thisyear);
                    $end = mktime(23, 59, 59, $thismonth, $thisday - 1, $thisyear);
                    break;
                case 'week':
                    //php获取本周起始时间戳和结束时间戳
                    $begin = mktime(0, 0, 0, $thismonth, $thisday - $thisweekday, $thisyear);
                    $end = mktime(23, 59, 59, $thismonth, $thisday - $thisweekday + 7 - 1, $thisyear);
                    break;
                case 'lastweek':
                    //php获取上周起始时间戳和结束时间戳
                    $begin = mktime(0, 0, 0, $thismonth, $thisday - $thisweekday - 7, $thisyear);
                    $end = mktime(23, 59, 59, $thismonth, $thisday - $thisweekday - 1, $thisyear);
                    break;
                case 'lastmonth':
                    //php获取上月起始时间戳和结束时间戳
                    $begin = mktime(0, 0, 0, $thismonth - 1, 1, $thisyear);
                    $end = mktime(23, 59, 59, $thismonth - 1, date('t', strtotime('last month')), $thisyear);
                    break;
                case 'month':
                    //php获取本月起始时间戳和结束时间戳
                    $begin = mktime(0, 0, 0, $thismonth, 1, $thisyear);
                    $end = mktime(23, 59, 59, $thismonth, date('t'), $thisyear);
                    break;
            }
            if ($lv !== 'all') {
                $hawalist    = $hawalist->where('TransitEndTime', '>', date('Y-m-d H:i:s', $begin))->where('TransitEndTime', '<', date('Y-m-d H:i:s', $end));
                $receiptlist = $receiptlist->where('BussinessTime', '>', date('Y-m-d H:i:s', $begin))->where('BussinessTime', '<', date('Y-m-d H:i:s', $end));
                $contract = $contract->where('SettlementTime', '>', date('Y-m-d H:i:s', $begin))->where('SettlementTime', '<', date('Y-m-d H:i:s', $end));
                $customer = $customer->where('VisitTime', '>', date('Y-m-d H:i:s', $begin))->where('VisitTime', '<', date('Y-m-d H:i:s', $end));

            }
            $company = $hawalist;
            //订单个数
            $rdata[$lv]['count'] = $hawalist->count();
            //产废单位count
            $rdata[$lv]['company'] = $company->distinct(true)->count('CompanyId');
            //产废单位count/
            $rdata[$lv]['customer'] = $customer->distinct(true)->count('CustomerId');
            //产废单位count
            $rdata[$lv]['contract'] = $contract->distinct(true)->count('CompanyId');
            //接受量cout
            $receiptlistid = $receiptlist->column('ReceiptListId');
            if (!empty($receiptlistid)) {
                $rdata[$lv]['weight'] = Receipt::where('ReceiptListId', 'in', $receiptlistid)->sum('Weight');
                $rdata[$lv]['weight'] =  $rdata[$lv]['weight'].'';
            } else {
                $rdata[$lv]['weight'] = 0;
            }
        }
        return myok($rdata);
    }
    
    //微观数据：每个业务员对应的跟进数，合同数
    public function busslist(){
        self::is_login();
        $now = input('starttime');
        $end = input('endtime');
        if(empty($now)){
            $now = date('Y-m-01',time());
        }
        if(empty($end)){
            $end = date('Y-m-d H:i:s',time());
        }
        $userid = [];
        //合同情况
        $sb = Contract::getsummary($now,$end);
        $contract = $sb['userlist'];
        foreach ($contract as $key => $value) {
            $userlist[$value['BussinessId']] = $value;
            $userlist[$value['BussinessId']]['VisitCount'] = 0;
            $userid[] = $value['BussinessId'];
        }

        //客户回访情况
        $customervisit = Customervisit::getsummary($now,$end);
        foreach ($customervisit as $key => $value) {
            $userid[] = $key;
            if(!empty($userlist[$key])){
                $userlist[$key]['VisitCount'] = $value['Count'];
            }else{
                $userlist[$key] = ['BussinessId'=>$key,'Price'=>0,'Count'=>0,'VisitCount'=>$value['Count']];
            }
        }

        //将业务员名放入里面
        $userinfo = UserModel::where('UserId','in',$userid)->column('Name','UserId');
        $contract = [];
        foreach ($userinfo as $key => $value) {
            $userlist[$key]['Name'] = $value;
            $contract[] = $userlist[$key];
        }
        return myok($contract);
    }
    
    //客户列表：客户电话/客户名称搜索
    public function  getcustomerlist(){
        self::is_login();
        $key = trim(input('searchkey'));
        $endtime = input('end');
        $startTime = input('start');
        $customerwhere = input('customer_where');//客户筛选
        $time = input('time_where');//时间筛选


        if($key=="%"){return moerr('非法参数');}
        $idata = input('post.');
        //定位
        if(!empty($idata['lat'])){
            $sdata['field'] = [str_distance($idata['lat'],$idata['lon'])];
            $sdata['order'] = 'distance asc';
            $sdata['where'][] = ['lat','<>','is NULL'];
        }
        //页码
        $pages  = input('pages');
        if(!empty($pages)){
            $sdata['pageindex'] = $pages;
        }

        //关键词
        if(!empty($key)){
            $sdata['where'][] = ['(Name like "%'.$key.'%")or(Address like "%'.$key.'%")or(UserName like "%'.$key.'%")or(UserTel like "%'.$key.'%")or(Tel like "%'.$key.'%")'];
        }

        //输出限制
        $limit  = input('limit');
        if(!empty($limit)){
            $sdata['p_limit'] = $limit;
        }else{
            $sdata['p_limit'] = 100;
        }

        //合同筛选
        if(!empty($customerwhere)){
            $today = date('Y-m-d H:i:s',time());
            $companyId = Contract::where('StartTime','<=',$today)->where('EndTime','>=',$today)->where('State',Contract::STATEOK)->column('CompanyId');
            switch ($customerwhere) {
                case 'cunzai'://存在生效的合同
                    $sdata['where'][] = ['CompanyId','in',$companyId];
                    break;
                case 'bucunzai'://不存在生效的合同
                    $sdata['where'][] = ['CompanyId not in ('.implode(',',$companyId).') or CompanyId is NULL'];
                    break;
            }
        }

        //时间选择
        if(!empty($endtime) && !empty($startTime)){
            $timefile = '';
            switch ($time) {
                case 'goutongshijian':
                    $customerId = Customervisit::where('VisitTime','>=',$startTime)->where('VisitTime','<=',$endtime.' 24:00')->column('CustomerId');
                    $sdata['where'][] = ['CustomerId','in',$customerId];
                    break;
                case 'tianjiashijian':
                    $sdata['where'][] = ['AddTime','>=',$startTime];
                    $sdata['where'][] = ['AddTime','<=',$endtime];
                    break;
                case 'hetongqianding':
                    $compnayId = Contract::where('SettlementTime','>=',$startTime)->where('SettlementTime','<=',$endtime.' 24:00')->column('CompanyId');
                    $sdata['where'][] = ['CompanyId','in',$compnayId];
                    break;
            }
        }
        
        //地图显示客户数据：
        //绿灯 存在生效的合同   黄灯（15天有跟进） 红灯（超过15天没跟进） 
        $sdata['Type'] = 'customer';
        $sb = Customermodel::usergetlist($sdata,'datascreen');
        $time = date('Y-m-d H:i:s',(time() - 30*24*60*60));
        foreach ($sb['list'] as $key => $value) {
            $sb['list'][$key]['statetext'] = $sb['statetext'][$value['State']];
            $sb['list'][$key]['guard_state_text'] = empty($value['guard_state'])?'':'保护中';
            $sb['list'][$key]['has_contract'] = empty($value['contractlist'])?false:true;
            $sb['list'][$key]['has_visit'] = $value['LastTime']>$time?true:false;
        }
        return myok($sb);
    }

    //获取客户信息
    public function getinfo(){
        self::is_login();
        $id = input('id');
        if(empty($id)){
            return myerr('缺少参数，请重新尝试');
        }
        $data = Customermodel::user_getinfo($id,'datascreen');
        if(empty($data)){
            return myerr('没有找到此客户');
        }
        if(!empty($data['CompanyId'])){
            $data['contract'] = Contract::getcompanycontractlist($data['CompanyId'],'datascreen');
        }
        $data['url'] = WEBURL.'print/contract_rote?p=';
        return myok($data);
    }

    /**
     * 获取订单
     * @return [type] [description]
     */
    public function getorderlist()
    {
        self::is_login();
        $car    = input('CarNumber');
        $number = input('number');
        $star   = input('start');
        $end    = input('end');
        $limit  = 30;
        $pages  = empty(input('pages')) ? 0 : input('pages') - 1;

        $data = HawaList::where('State', '<>', HawaList::STATEDELETE);
        if (!empty($car)) {
            $data = $data->where('TransitBrandNumber', 'like', '%' . $car . '%');
        }

        if (!empty($number)) {
            $data = $data->where('OrderNumber', 'like', '%' . $number . '%');
        }

        if (!empty($star)) {
            $data = $data->where('UpTime', '>=', $star);
        }

        if (!empty($end)) {
            $data = $data->where('UpTime', '<=', $end);
        }
        //总条数
        if (empty($rdata['count'])) {
            $rdata['count'] = $data->count();
        }

        $data = $data->with('companyinfo')->withSum('listinfo', 'Weight')->limit($pages * $limit, $limit)->order('UpTime desc')->visible(['HawaListId', 'State', 'UpTime', 'OrderNumber', 'ConfirmState', 'companyinfo.Name', 'companyinfo.CompanyId', 'companyinfo.Lat', 'companyinfo.Lon', 'companyinfo.Tel', 'TransitCompanyId', 'TransitCompanyName', 'TransitEscortName', 'TransitCompanyAddress', 'TransitNumber', 'TransitTel', 'TranSportId', 'TranSportType', 'TransitBrandNumber', 'TransitDriverId', 'TransitEscortId', 'TransitDrvierName', 'TransitDrvierTel', 'TransitUser', 'TransitEndPoint', 'TransitStartTime', 'TransitStartingPoint', 'TransitViaLand', 'listinfo_sum', 'TransitEndTime'])->select();

        foreach ($data as $key => $value) {
            $data[$key]['State'] = HawaList::getStatusText($value['State']);
        }
        $rdata['list'] = $data;

        return myok($rdata);
    }

     /**
     * 大屏登陆逻辑
     * @return boolean [description]
     */
    public static function login()
    {
        $p  = input('screen_password');
        $sb = Setting::login_screen_password($p);
        if (!$sb) {
            moerr('密码错误，请重新尝试');
        }else{
        	return myok('登陆成功');
        }
    }

    /**
     * 大屏检测登陆逻辑
     * @return boolean [description]
     */
    public static function is_login()
    {
        $p  = Request::header('token');
        if(empty($p)){
        	$p = '';
        }
        $sb = Setting::login_screen_password($p);
        if (!$sb) {
            moerr('请输入密码', '', 'relogin');
        }
    }
}
